package com.x.ant.util;

import com.x.framework.Base;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by x on 2017/10/16.
 */
public class PrintUtil {
    private static final Logger logger = LogManager.getLogger(PrintUtil.class);
    private static final String PRINT_URL = "http://api.feieyun.cn/Api/Open/";//不需要修改
    private static final String PRINT_USER = "460202085@qq.com";
    private static final String PRINT_UKEY = "qEcNbuWXHTIAeAzG";
    private static final String user = "user";
    private static final String stime = "stime";
    private static final String sig = "sig";
    private static final String apiname = "apiname";
    private static final String Open_printerAddlist = "Open_printerAddlist";
    private static final String Open_printMsg = "Open_printMsg";
    private static final String SN = "sn";
    private static final String printerContent = "printerContent";
    private static final String CONTENT = "content";
    private static final String times = "times";
    private static final String UTF8 = "utf-8";

    private static String addprinter(String snlist) {
        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(PRINT_URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(user, PRINT_USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair(stime, STIME));
        nvps.add(new BasicNameValuePair(sig, signature(STIME)));
        nvps.add(new BasicNameValuePair(apiname, Open_printerAddlist));//固定值,不需要修改
        nvps.add(new BasicNameValuePair(printerContent, snlist));

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, UTF8));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }

    public static String printBill(String printNum,
                                   String deptPrintSn,
                                   String deptName,
                                   String deptAddress,
                                   String taskSenderUserName,
                                   String taskSenderUserMobile,
                                   String taskLoadingArea,
                                   String taskLoadingAddress,
                                   String taskUnloadingArea,
                                   String taskUnloadingAddress,
                                   String taskGoodsStandard,
                                   int taskFreightPrice,
                                   String taskPayWay,
                                   String taskRemark,
                                   String truckUserName,
                                   String truckMobile,
                                   String truckNative,
                                   int truckNum,
                                   String truckPlates,
                                   String billCode,
                                   String staffUserMobile,
                                   String url) {
        String content = getBillContent(deptName,
                deptAddress,
                taskSenderUserName,
                taskSenderUserMobile,
                taskLoadingArea,
                taskLoadingAddress,
                taskUnloadingArea,
                taskUnloadingAddress,
                taskGoodsStandard,
                taskFreightPrice,
                taskPayWay,
                taskRemark,
                truckUserName,
                truckMobile,
                truckNative,
                truckNum,
                truckPlates,
                billCode,
                staffUserMobile,
                url);
        return print(printNum, deptPrintSn, content);
    }

    private static String getBillContent(String deptName,
                                         String deptAddress,
                                         String taskSenderUserName,
                                         String taskSenderUserMobile,
                                         String taskLoadingArea,
                                         String taskLoadingAddress,
                                         String taskUnloadingArea,
                                         String taskUnloadingAddress,
                                         String taskGoodsStandard,
                                         int taskFreightPrice,
                                         String taskPayWay,
                                         String taskRemark,
                                         String truckUserName,
                                         String truckMobile,
                                         String truckNative,
                                         int truckNum,
                                         String truckPlates,
                                         String billCode,
                                         String staffUserMobile,
                                         String url) {
        StringBuilder content = new StringBuilder("<LOGO><BR>");
        content.append("<CB>" + deptName + "货运协议</CB><BR>");
        content.append("甲方(托运方)：" + taskSenderUserName + " " + taskSenderUserMobile + "<BR>");
        content.append("乙方(承运方)：" + truckUserName + " " + truckMobile + "<BR>");
        content.append("车主籍贯：" + truckNative + "<BR>");
        content.append("提货单号：" + billCode + "<BR>");
        content.append("车牌号：" + truckPlates + "<BR>");
        content.append("经协商甲、乙双方自愿达成如下协议：<BR>");
        content.append("甲方委托乙方承运货物 " + taskGoodsStandard + "，数量 " + truckNum + " 件，由 " + taskLoadingArea + "   <B>" + taskLoadingAddress +
                "</B>   至 " + taskUnloadingArea + " " + taskUnloadingAddress +
                "。全程运费 " + taskFreightPrice + " 元／吨，运费支付方式货到 " + taskPayWay + " 付清。<BR>");
        content.append("<C>更多协议条款，请扫描二维码查看</C><BR>");
        content.append("<C><QR>" + url + "</QR></C><BR>");
        content.append("备注：" + taskRemark + "<BR>");
        content.append("甲方经办人：             乙方经办人：         <BR>");
        content.append("中介：" + deptName + "<BR>");
        content.append("地址：" + deptAddress + "<BR>");
        content.append("经办人：<BR>");

        content.append("<RIGHT>" + Base.getCurrentDate(0, "yyyy-MM-dd hh:mm:ss") + "</RIGHT><BR>");
        content.append("<CB>客服电话：" + staffUserMobile + "</CB>");
        return content.toString();
    }


    //方法1
    private static String print(String num, String sn, String content) {
        //标签说明：
        //单标签:
        //"<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
        //"<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
        //成对标签：
        //"<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
        //<W></W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,"<RIGHT></RIGHT>"为右对齐
        //拼凑订单内容时可参考如下格式
        //根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式

//        String content;
//        content = "<CB>测试打印</CB><BR>";
//        content += "名称　　　　　 单价  数量 金额<BR>";
//        content += "--------------------------------<BR>";
//        content += "饭　　　　　　 1.0    1   1.0<BR>";
//        content += "炒饭　　　　　 10.0   10  10.0<BR>";
//        content += "蛋炒饭　　　　 10.0   10  100.0<BR>";
//        content += "鸡蛋炒饭　　　 100.0  1   100.0<BR>";
//        content += "番茄蛋炒饭　　 1000.0 1   100.0<BR>";
//        content += "西红柿蛋炒饭　 1000.0 1   100.0<BR>";
//        content += "西红柿鸡蛋炒饭 100.0  10  100.0<BR>";
//        content += "备注：加辣<BR>";
//        content += "--------------------------------<BR>";
//        content += "合计：xx.0元<BR>";
//        content += "送货地点：广州市南沙区xx路xx号<BR>";
//        content += "联系电话：13888888888888<BR>";
//        content += "订餐时间：2016-08-08 08:08:08<BR>";
//        content += "<QR>http://www.dzist.com</QR>";

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(PRINT_URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(user, PRINT_USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair(stime, STIME));
        nvps.add(new BasicNameValuePair(sig, signature(STIME)));
        nvps.add(new BasicNameValuePair(apiname, Open_printMsg));//固定值,不需要修改
        nvps.add(new BasicNameValuePair(SN, sn));
        nvps.add(new BasicNameValuePair(CONTENT, content));
        nvps.add(new BasicNameValuePair(times, num));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, UTF8));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                    logger.error(printerContent + result);
                }
            }
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error(e);
            }
            try {
                post.abort();
            } catch (Exception e) {
                logger.error(e);
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        return result;
    }

    //生成签名字符串
    private static String signature(String STIME) {
        return DigestUtils.sha1Hex(PRINT_USER + PRINT_UKEY + STIME);
    }
}
